import os
import sys
from pathlib import Path
project_dir = os.path.join(Path(__file__).resolve().parent,'webapiback')
def add_to_path(new_path):
    abs_path = os.path.abspath(new_path)
    sys.path.append(abs_path)
sys.path.append(project_dir)
add_to_path(project_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings")

import django,json

def setup_django_settings():
    from django.conf import settings
    from webapiback.settings import settings as webapiback_settings
    webapiback_settings.LOGGING_CONFIG = None
    settings.configure(
        webapiback_settings
    )
#setup_django_settings()
django.setup()
from django.http import HttpRequest
routed_urls = {}    

#获取Django路由表并且映射到本地路由表目前只支持2级路由
#路由表格式：{路由:回调函数}
def setup_django_urls():
    from django.urls import get_resolver
    resolver = get_resolver(None)
    for url_pattern in resolver.url_patterns:
        base_pattern = str(url_pattern.pattern)
        if hasattr(url_pattern, 'url_patterns'):
            for sub_url_pattern in url_pattern.url_patterns:
                routed_urls[base_pattern + str(sub_url_pattern.pattern)] = sub_url_pattern.callback
        else:
            routed_urls[base_pattern] = url_pattern.callback

#获取Django响应
#request_path: 请求路径
#request_method: 请求方法
#request_body: 请求体
def get_django_response(request_path, request_method, request_body,token=None):
    request = HttpRequest()
    request.method = request_method
    request.path = request_path
    request.META['CONTENT_TYPE'] = 'application/json'
    if token:
        request.META['HTTP_AUTHORIZATION'] = 'Bearer '+token
    try:
        body_stream = json.dumps(request_body).encode('utf-8')
    except  Exception as e:
        return {"code": 500, "msg": "请求体解析失败"}
    request._body = body_stream
    request._read_started = True
    request.META['CONTENT_LENGTH'] = len(body_stream)
    try:
        response = routed_urls[request_path](request)
    except Exception as e:
        return {"code": 500, "msg": "%s" %e}
    
    return response.data


if __name__ == '__main__':
    """setup_django_urls()
    request_path = 'base/queryModel/'
    request_method = 'POST'
    token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzI0MjMxNTE4LCJpYXQiOjE3MjQyMjU1MTgsImp0aSI6IjU2OGU2ZTU4MWU0MzQ4MDg5ZDE4ZjQxNWU4ZTk2NzI0IiwidXNlcl9pZCI6MiwiaXNzIjoic253ZWJhcGkifQ.0Bd71944Vh8ZgsOiM8yDLg8cBUaaGUozN5CRBDfHd0c"
    request_body = {
        "appName": "base",
        "modelName": "Permission",
        "query": {
            "type__contains": "menu"
        },
        "exclude": {
            "type": "menu_dir"
        },
        "order_by": "id",
        "desc": True
    }
    res = get_django_response(request_path, request_method, request_body,token=None)
    
    print(json.dumps(res, indent=4, ensure_ascii=False))"""
    from webapiback.base.auth import create_default_user_password
    create_default_user_password()

